package org.bjf.utils;

import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

/**
 * @author jicexosl
 * @date 2018/1/22
 */
public final class ClientFactory {

    private static EsConfig esConfig;

    private ClientFactory() {
    }

    private static class Singleton {
        private static RestHighLevelClient client;

        static {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(esConfig.getUsername(),
                        esConfig.getPassword()));

            client = new RestHighLevelClient(
                    RestClient.builder(esConfig.getHost()
                            .stream()
                            .map(v -> {
                                String[] s = v.split(":");
                                return new HttpHost(s[0], Integer.parseInt(s[1]), esConfig.getScheme());
                            }).toArray(HttpHost[]::new))
                            .setRequestConfigCallback((config) -> {
                                config.setConnectionRequestTimeout(0)
                                        .setSocketTimeout(esConfig.getSocketTimeout())
                                        .setConnectTimeout(esConfig.getConnectTimeout());
                                return config;

                            })
                            .setMaxRetryTimeoutMillis(esConfig.getRetryTimeout())
                            .setHttpClientConfigCallback(httpAsyncClientBuilder ->
                                    httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
            );

            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    if (client != null) {
                        try {
                            client.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    }


    public static RestHighLevelClient getClient() {
        return Singleton.client;
    }
}
